
<!DOCTYPE html>
<html lang="en">
    <!--百度统计-->
    <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?b94bd2699a7baf9292dd9cf571f7fbb9";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
    </script>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="keywords" content="Python,Django,Python教程,Django教程,教程,基础教程,Web开发,运维,自动化,博客,编程,软件,云计算,大数据,爬虫,
    人工智能,机器学习,神经网络" />
    <meta name="description" content="提供Python和Django的原创中文精品教程和博客,分享技术知识,传播新闻视点,提倡开源精神,让更多开发者从中受益。">
    <meta name="author" content="刘江,liujiang,大江东流">
    <title>
    
    django Part 2：模型与管理后台 - 刘江的django教程
    
</title>
	
	<!-- core CSS -->
    <link href="static/bootstrap.min.css" rel="stylesheet">
    <link href="static/font-awesome.min.css" rel="stylesheet">


    <link href="static/main.css" rel="stylesheet">

    <link href="static/github.css" rel="stylesheet">
    <!--[if lt IE 9]>
    <script src="js/html5shiv.js"></script>
    <script src="js/respond.min.js"></script>
    <![endif]-->       
    <link rel="shortcut icon" href="/static/images/ico/favicon.ico">
    
    <link href="static/course.css" rel="stylesheet">


</head><!--/head-->

<body class="homepage">

    <header id="header" class=" navbar-fixed-top">
        <div class="top-bar">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-md-6">
                        <div class="top-number">
                            <p><i class="fa fa-feed" aria-hidden="true"></i>&nbsp;
                            <strong style="color: red;">强烈推荐博主精心录制的Python及Django视频教程,<a href="/video/">详情点击</a>!</strong>
                            </p></div>
                    </div>
                    <div class="col-md-offset-3 col-md-3">
                        <span class="pull-left">分享：</span>
                        <!-- JiaThis Button BEGIN社会化分享工具 -->
                        <div class="jiathis_style_24x24">
                            <a class="jiathis_button_qzone"></a>
                            <a class="jiathis_button_tsina"></a>
                            <a class="jiathis_button_tqq"></a>
                            <a class="jiathis_button_weixin"></a>
                            <a class="jiathis_button_renren"></a>
                            <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jtico jtico_jiathis" target="_blank"></a>
                        </div>

                        <!-- JiaThis Button END -->
                    </div>
                </div>
            </div><!--/.container-->
        </div><!--/.top-bar-->

		<nav class="navbar navbar-default navbar-inverse">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#my-navbar" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="/">刘江的博客及教程</a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="my-navbar">
      <ul class="nav navbar-nav">
        <li><a href="/news/">新闻</a></li>
        <li><a href="/blog/">博客</a></li>
        <li><a href="/course/python/1">Python教程</a></li>
        <li><a href="2.html">Django教程</a></li>
        <li><a href="/video/">视频教程</a>
        <span class="badge" style="color: red;text-shadow:-1px 0 white,0 1px white,1px 0 white,0 -1px white; float: right;font-size: small;margin-left: -8px;">Hot!</span>
        </li>
      </ul>

      <form id="search-form" method="get" action="/blog/search/" class="navbar-form navbar-left collasped">
        <div class="form-group">
          <input type="text" name="keyword" class="form-control" placeholder="Search" required>
        </div>
        <button type="submit" class="btn btn-default"><span class="glyphicon glyphicon-search"></span></button>
      </form>

      <ul class="nav navbar-nav navbar-right">
          <li>
            
              <!--通过在login后添加next参数，让用户登录后返回先前的页面-->
            <a href="88.html">
            <span class="glyphicon glyphicon-log-in"></span>登录</a></li>
            
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>

    </header><!--/header-->


    
    <div class="container-fluid main">
      <div class="row">

        <!-- 左侧目录栏 -->
        <div class="col-md-3">
          <div class="navbar-sider list-group-item">
            目&nbsp;录
            <hr />
            
                
                        
                            
                            <a href="2.html" class="list-group-item"><b>Django教程</b></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="84.html"
                               class="list-group-item"><strong>Django简介</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="85.html"
                               class="list-group-item"><strong>Django环境安装</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="86.html"
                               class="list-group-item"><strong>第一个Django应用</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="87.html"
                               class="list-group-item">Part 1：请求与响应</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="88.html"
                               class="list-group-item active">Part 2：模型与管理后台</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="89.html"
                               class="list-group-item">Part 3：视图和模板</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="90.html"
                               class="list-group-item">Part 4：表单和类视图</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="91.html"
                               class="list-group-item">Part 5：测试</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="92.html"
                               class="list-group-item">Part 6：静态文件</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="93.html"
                               class="list-group-item">Part 7：自定义admin站点</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="94.html"
                               class="list-group-item"><strong>第一章：模型层model layer</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="95.html"
                               class="list-group-item">模型和字段</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="96.html"
                               class="list-group-item">关系类型字段</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="97.html"
                               class="list-group-item">字段的参数</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="98.html"
                               class="list-group-item">多对多中间表详解</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="99.html"
                               class="list-group-item">模型的元数据Meta</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="100.html"
                               class="list-group-item">模型的继承</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="101.html"
                               class="list-group-item">用包来组织模型</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="129.html"
                               class="list-group-item">查询操作</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="130.html"
                               class="list-group-item">查询集API</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="131.html"
                               class="list-group-item">不返回QuerySets的API</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="132.html"
                               class="list-group-item">字段查询参数及聚合函数</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="133.html"
                               class="list-group-item"><strong>第二章：视图层view layer</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="182.html"
                               class="list-group-item">Django2.0 URL配置</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="134.html"
                               class="list-group-item">URL路由基础</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="135.html"
                               class="list-group-item">路由转发</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="136.html"
                               class="list-group-item">URL反向解析和命名空间</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="137.html"
                               class="list-group-item">视图函数及快捷方式</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="138.html"
                               class="list-group-item">HttpRequest对象</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="139.html"
                               class="list-group-item">QueryDict对象</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="140.html"
                               class="list-group-item">HttpResponse对象</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="141.html"
                               class="list-group-item">文件上传</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="142.html"
                               class="list-group-item">动态生成CSV文件</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="143.html"
                               class="list-group-item">动态生成PDF文件</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="144.html"
                               class="list-group-item"><strong>第三章：模版层Template layer</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="145.html"
                               class="list-group-item">Django模板语言详解</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="146.html"
                               class="list-group-item">Django内置模板标签</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="147.html"
                               class="list-group-item">Django内置模版过滤器</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="148.html"
                               class="list-group-item">特殊的标签和过滤器</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="149.html"
                               class="list-group-item">人类可读性</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="150.html"
                               class="list-group-item">自定义模板标签和过滤器</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="151.html"
                               class="list-group-item"><strong>第四章：Django表单</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="152.html"
                               class="list-group-item">使用表单</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="153.html"
                               class="list-group-item">Django表单API详解</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="154.html"
                               class="list-group-item">Django表单字段汇总</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="155.html"
                               class="list-group-item">表单的Widgets</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="156.html"
                               class="list-group-item">模型表单ModelForm</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="157.html"
                               class="list-group-item"><strong>第五章：Admin管理后台</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="158.html"
                               class="list-group-item">自定制Admin</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="159.html"
                               class="list-group-item">自定义Admin actions</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="160.html"
                               class="list-group-item">Admin文档生成器</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="162.html"
                               class="list-group-item"><strong>第六章：Django 综合篇</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="163.html"
                               class="list-group-item">配置 Django</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="164.html"
                               class="list-group-item">核心配置项</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="165.html"
                               class="list-group-item">使用MySQL数据库</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="166.html"
                               class="list-group-item">django-admin和manage.py</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="167.html"
                               class="list-group-item">自定义django-admin命令</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="168.html"
                               class="list-group-item">会话session</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="169.html"
                               class="list-group-item">网站地图sitemap</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="170.html"
                               class="list-group-item">信号 signal</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="171.html"
                               class="list-group-item">序列化 serializers</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="172.html"
                               class="list-group-item">消息框架 message</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="173.html"
                               class="list-group-item">分页 Paginator</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="174.html"
                               class="list-group-item">聚合内容 RSS/Atom</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="175.html"
                               class="list-group-item">发送邮件</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="176.html"
                               class="list-group-item">Django 日志</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="177.html"
                               class="list-group-item">Django与缓存</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="178.html"
                               class="list-group-item">认证系统 Authentication</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="179.html"
                               class="list-group-item">Django与CSRF 、AJAX</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="180.html"
                               class="list-group-item">Django 国际化和本地化</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="181.html"
                               class="list-group-item">部署 Django</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="102.html"
                               class="list-group-item"><strong>实战一：用户登录与注册系统</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="103.html"
                               class="list-group-item">1. 搭建项目环境</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="104.html"
                               class="list-group-item">2. 设计数据模型</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="105.html"
                               class="list-group-item">3. admin后台</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="106.html"
                               class="list-group-item">4. url路由和视图</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="107.html"
                               class="list-group-item">5. 前端页面设计</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="108.html"
                               class="list-group-item">6. 登录视图</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="109.html"
                               class="list-group-item">7. Django表单</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="110.html"
                               class="list-group-item">8. 图片验证码</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="111.html"
                               class="list-group-item">9. session会话</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="112.html"
                               class="list-group-item">10. 注册视图</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="113.html"
                               class="list-group-item">11.使用Django发送邮件</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="114.html"
                               class="list-group-item">12. 邮件注册确认</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="115.html"
                               class="list-group-item">13. 使用Github管理项目</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="116.html"
                               class="list-group-item"><strong>实战二：CMDB之资产管理系统</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="117.html"
                               class="list-group-item">1.项目需求分析</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="118.html"
                               class="list-group-item">2.模型设计</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="119.html"
                               class="list-group-item">3.数据收集客户端</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="120.html"
                               class="list-group-item">4.Windows下收集数据</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="121.html"
                               class="list-group-item">5.Linux下收集数据</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="122.html"
                               class="list-group-item">6.新资产待审批区</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="123.html"
                               class="list-group-item">7.审批新资产</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="124.html"
                               class="list-group-item">8.已上线资产信息更新</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="125.html"
                               class="list-group-item">9.前端框架AdminLTE</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="126.html"
                               class="list-group-item">10.资产总表</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="127.html"
                               class="list-group-item">11.资产详细页面</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="128.html"
                               class="list-group-item">12.dashboard仪表盘</a>
                            
                        
                
            
          </div>
        </div>
        <!-- 左侧目录栏 结束 -->

        <!-- 右侧正文栏 -->
        <div class="col-md-9">
            <!-- 教程正文主体部分 -->
            <div class="row">
                <h1>Part 2：模型与管理后台</h1>
                <p>阅读:&nbsp;10589</p>
                <hr/>
                <p>接着第一部分，本节将讲述如何安装数据库，编写第一个模型以及简要的介绍下Django自动生成的后台管理admin站点。</p>
<h2 id="_1">一、数据库安装</h2>
<p>打开<code>mysite/settings.py</code>配置文件，这是整个Django项目的设置中心。Django默认使用SQLite数据库，因为Python源生支持SQLite数据库，所以你无须安装任何程序，就可以直接使用它。当然，如果你是在创建一个实际的项目，可以使用类似PostgreSQL的数据库，避免以后数据库迁移的相关问题。</p>
<div class="codehilite"><pre><span></span># mysite/settings.py

# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    &#39;default&#39;: {
        &#39;ENGINE&#39;: &#39;django.db.backends.sqlite3&#39;,
        &#39;NAME&#39;: os.path.join(BASE_DIR, &#39;db.sqlite3&#39;),
    }
}
</pre></div>


<p>如果你想使用其他的数据库，请先安装相应的数据库操作模块，并将settings文件中DATABASES位置的<code>’default’</code>的键值进行相应的修改，用于连接你的数据库。其中：</p>
<ul>
<li>
<p>ENGINE（引擎）：可以是<code>django.db.backends.sqlite3</code>、<code>django.db.backends.postgresql</code>、<code>django.db.backends.mysql</code>、<code>django.db.backends.oracle</code>，当然其它的也行。</p>
</li>
<li>
<p>NAME（名称）：类似Mysql数据库管理系统中用于保存项目内容的数据库的名字。如果你使用的是默认的SQLite，那么数据库将作为一个文件将存放在你的本地机器内，此时的NAME应该是这个文件的完整绝对路径包括文件名，默认值<code>os.path.join(BASE_DIR, ’db.sqlite3’)</code>，将把该文件储存在你的项目目录下。</p>
</li>
</ul>
<p>如果你不是使用默认的SQLite数据库，那么一些诸如USER，PASSWORD和HOST的参数必须手动指定！下面给出一个基于pymysql操作Mysql数据库的例子，更多细节参考后续的数据库章节。</p>
<div class="codehilite"><pre><span></span><span class="c1"># mysite/settings.py</span>

<span class="c1"># Database</span>
<span class="c1"># https://docs.djangoproject.com/en/1.11/ref/settings/#databases</span>

<span class="kn">import</span> <span class="nn">pymysql</span>         <span class="c1"># 一定要添加这两行！通过pip install pymysql！</span>
<span class="n">pymysql</span><span class="o">.</span><span class="n">install_as_MySQLdb</span><span class="p">()</span>

<span class="n">DATABASES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;ENGINE&#39;</span><span class="p">:</span> <span class="s1">&#39;django.db.backends.mysql&#39;</span><span class="p">,</span>
        <span class="s1">&#39;NAME&#39;</span><span class="p">:</span> <span class="s1">&#39;mysite&#39;</span><span class="p">,</span>
        <span class="s1">&#39;HOST&#39;</span><span class="p">:</span> <span class="s1">&#39;192.168.1.1&#39;</span><span class="p">,</span>
        <span class="s1">&#39;USER&#39;</span><span class="p">:</span> <span class="s1">&#39;root&#39;</span><span class="p">,</span>
        <span class="s1">&#39;PASSWORD&#39;</span><span class="p">:</span> <span class="s1">&#39;pwd&#39;</span><span class="p">,</span>
        <span class="s1">&#39;PORT&#39;</span><span class="p">:</span> <span class="s1">&#39;3306&#39;</span><span class="p">,</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>


<p>注意：</p>
<ul>
<li>在使用非SQLite的数据库时，请务必预先在数据库管理系统的提示符交互模式下创建数据库，你可以使用命令：“CREATE DATABASE database_name;”。Django不会自动帮你做这一步工作。</li>
<li>确保你在settings文件中提供的数据库用户具有创建数据库表的权限，因为在接下来的教程中，我们需要自动创建一个test数据表。（在实际项目中也需要确认这一条要求。）</li>
<li>如果你使用的是SQLite，那么你无需做任何预先配置，直接使用就可以了。</li>
</ul>
<p>在修改settings文件时，请顺便将<code>TIME_ZONE</code>设置为国内所在的时区<code>Asia/Shanghai</code>。</p>
<p>同时，请注意settings文件中顶部的<code>INSTALLED_APPS</code>设置项。它列出了所有的项目中被激活的Django应用（app）。你必须将你自定义的app注册在这里。每个应用可以被多个项目使用，并且可以打包和分发给其他人在他们的项目中使用。</p>
<p>默认情况，<code>INSTALLED_APPS</code>中会自动包含下列条目，它们都是Django自动生成的：</p>
<ul>
<li>django.contrib.admin：admin管理后台站点</li>
<li>django.contrib.auth：身份认证系统</li>
<li>django.contrib.contenttypes：内容类型框架</li>
<li>django.contrib.sessions：会话框架</li>
<li>django.contrib.messages：消息框架</li>
<li>django.contrib.staticfiles：静态文件管理框架</li>
</ul>
<p>上面的一些应用也需要建立一些数据库表，所以在使用它们之前我们要在数据库中创建这些表。使用下面的命令创建数据表：</p>
<div class="codehilite"><pre><span></span>$ python manage.py migrate。
</pre></div>


<p>migrate命令将遍历<code>INSTALLED_APPS</code>设置中的所有项目，在数据库中创建对应的表，并打印出每一条动作信息。如果你感兴趣，可以在你的数据库命令行下输入：<code>\dt</code> (PostgreSQL)、 <code>SHOW TABLES;</code>(MySQL)或 <code>.schema</code>(SQLite) 来列出 Django 所创建的表。</p>
<p>提示：对于极简主义者，你完全可以在INSTALLED_APPS内注释掉任何或者全部的Django提供的通用应用。这样，migrate也不会再创建对应的数据表。</p>
<h2 id="_2">二、创建模型</h2>
<p>现在，我们来定义模型model，模型本质上就是数据库表的布局，再附加一些元数据。</p>
<p>Django通过自定义Python类的形式来定义具体的模型，每个模型的物理存在方式就是一个Python的类Class，每个模型代表数据库中的一张表，每个类的实例代表数据表中的一行数据，类中的每个变量代表数据表中的一列字段。Django通过模型，将Python代码和数据库操作结合起来，实现对SQL查询语言的封装。也就是说，你可以不会管理数据库，可以不会SQL语言，你同样能通过Python的代码进行数据库的操作。Django通过ORM对数据库进行操作，奉行代码优先的理念，将Python程序员和数据库管理员进行分工解耦。</p>
<p>在这个简单的投票应用中，我们将创建两个模型：<code>Question</code>和<code>Choice</code>。Question包含一个问题和一个发布日期。Choice包含两个字段：该选项的文本描述和该选项的投票数。每一条Choice都关联到一个Question。这些都是由Python的类来体现，编写的全是Python的代码，不接触任何SQL语句。现在，编辑<code>polls/models.py</code>文件，具体代码如下：</p>
<div class="codehilite"><pre><span></span><span class="c1"># polls/models.py</span>

<span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Question</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">question_text</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">200</span><span class="p">)</span>
    <span class="n">pub_date</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateTimeField</span><span class="p">(</span><span class="s1">&#39;date published&#39;</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">Choice</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">question</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Question</span><span class="p">,</span> <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">)</span>
    <span class="n">choice_text</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">200</span><span class="p">)</span>
    <span class="n">votes</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">(</span><span class="n">default</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
</pre></div>


<p>上面的代码非常简单明了。每一个类都是<code>django.db.models.Model</code>的子类。每一个字段都是<code>Field</code>类的一个实例，例如用于保存字符数据的CharField和用于保存时间类型的DateTimeField，它们告诉Django每一个字段保存的数据类型。</p>
<p>每一个Field实例的名字就是字段的名字（如： question_text 或者 pub_date ）。在你的Python代码中会使用这个值，你的数据库也会将这个值作为表的列名。</p>
<p>你也可以在每个Field中使用一个可选的第一位置参数用于提供一个人类可读的字段名，让你的模型更友好，更易读，并且将被作为文档的一部分来增强代码的可读性。</p>
<p>一些Field类必须提供某些特定的参数。例如CharField需要你指定max_length。这不仅是数据库结构的需要，同样也用于数据验证功能。</p>
<p>有必填参数，当然就会有可选参数，比如在votes里我们将其默认值设为0.</p>
<p>最后请注意，我们使用<code>ForeignKey</code>定义了一个外键关系。它告诉Django，每一个Choice关联到一个对应的Question（注意要将外键写在‘多’的一方）。Django支持通用的数据关系：一对一，多对一和多对多。</p>
<h2 id="_3">三、启用模型</h2>
<p>上面的代码看着有点少，其实包含了大量的信息，据此，Django会做下面两件事：</p>
<ul>
<li>创建该app对应的数据库表结构</li>
<li>为Question和Choice对象创建基于Python的数据库访问API</li>
</ul>
<p>但是，首先我们得先告诉Django项目，我们要使用投票app。</p>
<p>要将应用添加到项目中，需要在<code>INSTALLED_APPS</code>设置中增加指向该应用的配置文件的链接。对于本例的投票应用，它的配置类文件是<code>polls/apps.py</code>，路径格式为<code>polls.apps.PollsConfig</code>。我们需要在<code>INSTALLED_APPS</code>中，将该路径添加进去：</p>
<div class="codehilite"><pre><span></span># mysite/settings.py

INSTALLED_APPS = [
&#39;polls.apps.PollsConfig&#39;,
&#39;django.contrib.admin&#39;,
&#39;django.contrib.auth&#39;,
&#39;django.contrib.contenttypes&#39;,
&#39;django.contrib.sessions&#39;,
&#39;django.contrib.messages&#39;,
&#39;django.contrib.staticfiles&#39;,
]
</pre></div>


<p>实际上，在多数情况下，我们简写成‘polls’就可以了：</p>
<div class="codehilite"><pre><span></span># mysite/settings.py

INSTALLED_APPS = [
&#39;polls&#39;,
&#39;django.contrib.admin&#39;,
&#39;django.contrib.auth&#39;,
&#39;django.contrib.contenttypes&#39;,
&#39;django.contrib.sessions&#39;,
&#39;django.contrib.messages&#39;,
&#39;django.contrib.staticfiles&#39;,
]
</pre></div>


<p>现在Django已经知道你的投票应用的存在了，并把它加入了项目大家庭。</p>
<p>我们需要再运行下一个命令：</p>
<div class="codehilite"><pre><span></span>$ python manage.py makemigrations polls
</pre></div>


<p>你会看到类似下面的提示：</p>
<div class="codehilite"><pre><span></span>Migrations for &#39;polls&#39;:
  polls/migrations/0001_initial.py:
    - Create model Choice
    - Create model Question
    - Add field question to choice
</pre></div>


<p>通过运行<code>makemigrations</code>命令，相当于告诉Django你对模型有改动，并且你想把这些改动保存为一个“迁移(migration)”。</p>
<p><code>migrations</code>是Django保存模型修改记录的文件，这些文件保存在磁盘上。在例子中，它就是<code>polls/migrations/0001_initial.py</code>，你可以打开它看看，里面保存的都是人类可读并且可编辑的内容，方便你随时手动修改。</p>
<p>接下来有一个叫做<code>migrate</code>的命令将对数据库执行真正的迁移动作。但是在此之前，让我们先看看在migration的时候实际执行的SQL语句是什么。有一个叫做<code>sqlmigrate</code>的命令可以展示SQL语句，例如：</p>
<div class="codehilite"><pre><span></span>$ python manage.py sqlmigrate polls <span class="m">0001</span>
</pre></div>


<p>你将会看到如下类似的文本（经过适当的格式调整，方便阅读）：</p>
<div class="codehilite"><pre><span></span>BEGIN;
--
-- Create model Choice
--
CREATE TABLE &quot;polls_choice&quot; (
    &quot;id&quot; serial NOT NULL PRIMARY KEY,
    &quot;choice_text&quot; varchar(200) NOT NULL,
    &quot;votes&quot; integer NOT NULL
);
--
-- Create model Question
--
CREATE TABLE &quot;polls_question&quot; (
    &quot;id&quot; serial NOT NULL PRIMARY KEY,
    &quot;question_text&quot; varchar(200) NOT NULL,
    &quot;pub_date&quot; timestamp with time zone NOT NULL
);
--
-- Add field question to choice
--
ALTER TABLE &quot;polls_choice&quot; ADD COLUMN &quot;question_id&quot; integer NOT NULL;
ALTER TABLE &quot;polls_choice&quot; ALTER COLUMN &quot;question_id&quot; DROP DEFAULT;
CREATE INDEX &quot;polls_choice_7aa0f6ee&quot; ON &quot;polls_choice&quot; (&quot;question_id&quot;);
ALTER TABLE &quot;polls_choice&quot;
    ADD CONSTRAINT &quot;polls_choice_question_id_246c99a640fbbd72_fk_polls_question_id&quot;
    FOREIGN KEY (&quot;question_id&quot;)
    REFERENCES &quot;polls_question&quot; (&quot;id&quot;)
    DEFERRABLE INITIALLY DEFERRED;
COMMIT;
</pre></div>


<p><strong>请注意：</strong></p>
<ul>
<li>实际的输出内容将取决于您使用的数据库会有所不同。上面的是PostgreSQL的输出。</li>
<li>表名是自动生成的，通过组合应用名 (polls) 和小写的模型名<code>question</code>和<code>choice</code> 。 ( 你可以重写此行为。)</li>
<li>主键 (IDs) 是自动添加的。( 你也可以重写此行为。)</li>
<li>按照惯例，Django 会在外键字段名上附加 "_id" 。 (你仍然可以重写此行为。)</li>
<li>生成SQL语句时针对你所使用的数据库，会为你自动处理特定于数据库的字段，例如 auto_increment (MySQL), serial (PostgreSQL), 或integer primary key (SQLite) 。 在引用字段名时也是如此 – 比如使用双引号或单引号。</li>
<li>这些SQL命令并没有在你的数据库中实际运行，它只是在屏幕上显示出来，以便让你了解Django真正执行的是什么。</li>
</ul>
<p>如果你感兴趣，也可以运行<code>python manage.py check</code>命令，它将检查项目中的错误，并不实际进行迁移或者链接数据库的操作。</p>
<p>现在，我们可以运行migrate命令，在数据库中进行真正的表操作了。</p>
<div class="codehilite"><pre><span></span>$ python manage.py migrate
Operations to perform:
    Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
    Rendering model states... DONE
    Applying polls.0001_initial... OK
</pre></div>


<p>migrate命令对所有还未实施的迁移记录进行操作，本质上就是将你对模型的修改体现到数据库中具体的表上面。Django通过一张叫做django_migrations的表，记录并跟踪已经实施的migrate动作，通过对比获得哪些migrations尚未提交。</p>
<p>migrations的功能非常强大，允许你随时修改你的模型，而不需要删除或者新建你的数据库或数据表，在不丢失数据的同时，实时动态更新数据库。我们将在后面的章节对此进行深入的阐述，但是现在，只需要记住<strong>修改模型时的操作分三步</strong>：</p>
<ul>
<li>在models.py中修改模型；</li>
<li>运行<code>python manage.py makemigrations</code>为改动创建迁移记录；</li>
<li>运行<code>python manage.py migrate</code>，将操作同步到数据库。</li>
</ul>
<p>之所以要将创建和实施迁移的动作分成两个命令两步走是因为你也许要通过版本控制系统（例如github，svn）提交你的项目代码，如果没有一个中间过程的保存文件（migrations），那么github如何知道以及记录、同步、实施你所进行过的模型修改动作呢？毕竟，github不和数据库直接打交道，也没法和你本地的数据库通信。但是分开之后，你只需要将你的migration文件（例如上面的0001）上传到github，它就会知道一切。</p>
<h2 id="api">四、使用模型的API</h2>
<p>下面，让我们进入Python交互环境，尝试使用Django提供的数据库访问API。要进入Python的shell，请输入命令：</p>
<div class="codehilite"><pre><span></span>$ python manage.py shell
</pre></div>


<p>相比较直接输入“python”命令的方式进入Python环境，调用<code>manage.py</code>参数能将<code>DJANGO_SETTINGS_MODULE</code>环境变量导入，它将自动按照<code>mysite/settings.py</code>中的设置，配置好你的python shell环境，这样，你就可以导入和调用任何你项目内的模块了。</p>
<p>或者你也可以这样，先进入一个纯净的python shell环境，然后启动Django，具体如下：</p>
<div class="codehilite"><pre><span></span><span class="o">&gt;&gt;&gt;</span> <span class="kn">import</span> <span class="nn">django</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">django</span><span class="o">.</span><span class="n">setup</span><span class="p">()</span>
</pre></div>


<p>当你进入shell后，尝试一下下面的API吧：</p>
<div class="codehilite"><pre><span></span>    <span class="o">&gt;&gt;&gt;</span> <span class="kn">from</span> <span class="nn">polls.models</span> <span class="kn">import</span> <span class="n">Question</span><span class="p">,</span> <span class="n">Choice</span> <span class="c1"># 导入我们写的模型类</span>
    <span class="c1"># 现在系统内还没有questions对象</span>
    <span class="o">&gt;&gt;&gt;</span> <span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
    <span class="o">&lt;</span><span class="n">QuerySet</span> <span class="p">[]</span><span class="o">&gt;</span>

    <span class="c1"># 创建一个新的question对象</span>
    <span class="c1"># Django推荐使用timezone.now()代替python内置的datetime.datetime.now()</span>
    <span class="c1"># 这个timezone就来自于Django唯一的依赖库pytz</span>
    <span class="kn">from</span> <span class="nn">django.utils</span> <span class="kn">import</span> <span class="n">timezone</span>
    <span class="o">&gt;&gt;&gt;</span> <span class="n">q</span> <span class="o">=</span> <span class="n">Question</span><span class="p">(</span><span class="n">question_text</span><span class="o">=</span><span class="s2">&quot;What&#39;s new?&quot;</span><span class="p">,</span> <span class="n">pub_date</span><span class="o">=</span><span class="n">timezone</span><span class="o">.</span><span class="n">now</span><span class="p">())</span>

    <span class="c1"># 你必须显式的调用save()方法，才能将对象保存到数据库内</span>
    <span class="o">&gt;&gt;&gt;</span> <span class="n">q</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>

    <span class="c1"># 默认情况，你会自动获得一个自增的名为id的主键</span>
    <span class="o">&gt;&gt;&gt;</span> <span class="n">q</span><span class="o">.</span><span class="n">id</span>
    <span class="mi">1</span>

    <span class="c1"># 通过python的属性调用方式，访问模型字段的值</span>
    <span class="o">&gt;&gt;&gt;</span> <span class="n">q</span><span class="o">.</span><span class="n">question_text</span>
    <span class="s2">&quot;What&#39;s new?&quot;</span>
    <span class="o">&gt;&gt;&gt;</span> <span class="n">q</span><span class="o">.</span><span class="n">pub_date</span>
    <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="p">(</span><span class="mi">2012</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">26</span><span class="p">,</span> <span class="mi">13</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">775217</span><span class="p">,</span> <span class="n">tzinfo</span><span class="o">=&lt;</span><span class="n">UTC</span><span class="o">&gt;</span><span class="p">)</span>

    <span class="c1"># 通过修改属性来修改字段的值，然后显式的调用save方法进行保存。</span>
    <span class="o">&gt;&gt;&gt;</span> <span class="n">q</span><span class="o">.</span><span class="n">question_text</span> <span class="o">=</span> <span class="s2">&quot;What&#39;s up?&quot;</span>
    <span class="o">&gt;&gt;&gt;</span> <span class="n">q</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>

    <span class="c1"># objects.all() 用于查询数据库内的所有questions</span>
    <span class="o">&gt;&gt;&gt;</span> <span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
    <span class="o">&lt;</span><span class="n">QuerySet</span> <span class="p">[</span><span class="o">&lt;</span><span class="n">Question</span><span class="p">:</span> <span class="n">Question</span> <span class="nb">object</span><span class="o">&gt;</span><span class="p">]</span><span class="o">&gt;</span>
</pre></div>


<p>这里等一下：上面的<code>&lt;Question: Question object&gt;</code>是一个不可读的内容展示，你无法从中获得任何直观的信息，为此我们需要一点小技巧，让Django在打印对象时显示一些我们指定的信息。</p>
<p>返回<code>polls/models.py</code>文件，修改一下question和Choice这两个类，代码如下：</p>
<div class="codehilite"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>
<span class="kn">from</span> <span class="nn">django.utils.encoding</span> <span class="kn">import</span> <span class="n">python_2_unicode_compatible</span>

<span class="nd">@python_2_unicode_compatible</span> <span class="c1"># 当你想支持python2版本的时候才需要这个装饰器</span>
<span class="k">class</span> <span class="nc">Question</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c1"># ...</span>
    <span class="k">def</span> <span class="fm">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>   <span class="c1"># 在python2版本中使用的是__unique__</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">question_text</span>

<span class="nd">@python_2_unicode_compatible</span> 
<span class="k">class</span> <span class="nc">Choice</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c1"># ...</span>
    <span class="k">def</span> <span class="fm">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">choice_text</span>
</pre></div>


<p>这个技巧不但对你打印对象时很有帮助，在你使用Django的admin站点时也同样有帮助。</p>
<p>另外，这里我们自定义一个模型的方法，用于判断问卷是否最近时间段内发布度的：</p>
<div class="codehilite"><pre><span></span><span class="kn">import</span> <span class="nn">datetime</span>
<span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>
<span class="kn">from</span> <span class="nn">django.utils</span> <span class="kn">import</span> <span class="n">timezone</span>

<span class="k">class</span> <span class="nc">Question</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c1"># ...</span>
    <span class="k">def</span> <span class="nf">was_published_recently</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">pub_date</span> <span class="o">&gt;=</span> <span class="n">timezone</span><span class="o">.</span><span class="n">now</span><span class="p">()</span> <span class="o">-</span> <span class="n">datetime</span><span class="o">.</span><span class="n">timedelta</span><span class="p">(</span><span class="n">days</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
</pre></div>


<p>请注意上面分别导入了两个关于时间的模块，一个是python内置的datetime一个是Django工具包提供的timezone。</p>
<p>保存修改后，我们重新启动一个新的python shell，再来看看其他的API：</p>
<div class="codehilite"><pre><span></span><span class="o">&gt;&gt;&gt;</span> <span class="kn">from</span> <span class="nn">polls.models</span> <span class="kn">import</span> <span class="n">Question</span><span class="p">,</span> <span class="n">Choice</span>

<span class="c1"># 先看看__str__()的效果，直观多了吧？</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="o">&lt;</span><span class="n">QuerySet</span> <span class="p">[</span><span class="o">&lt;</span><span class="n">Question</span><span class="p">:</span> <span class="n">What</span><span class="s1">&#39;s up?&gt;]&gt;</span>

<span class="c1"># Django提供了大量的关键字参数查询API</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="o">&lt;</span><span class="n">QuerySet</span> <span class="p">[</span><span class="o">&lt;</span><span class="n">Question</span><span class="p">:</span> <span class="n">What</span><span class="s1">&#39;s up?&gt;]&gt;</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">question_text__startswith</span><span class="o">=</span><span class="s1">&#39;What&#39;</span><span class="p">)</span>
<span class="o">&lt;</span><span class="n">QuerySet</span> <span class="p">[</span><span class="o">&lt;</span><span class="n">Question</span><span class="p">:</span> <span class="n">What</span><span class="s1">&#39;s up?&gt;]&gt;</span>

<span class="c1"># 获取今年发布的问卷</span>
<span class="o">&gt;&gt;&gt;</span> <span class="kn">from</span> <span class="nn">django.utils</span> <span class="kn">import</span> <span class="n">timezone</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">current_year</span> <span class="o">=</span> <span class="n">timezone</span><span class="o">.</span><span class="n">now</span><span class="p">()</span><span class="o">.</span><span class="n">year</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pub_date__year</span><span class="o">=</span><span class="n">current_year</span><span class="p">)</span>
<span class="o">&lt;</span><span class="n">Question</span><span class="p">:</span> <span class="n">What</span><span class="s1">&#39;s up?&gt;</span>

<span class="c1"># 查询一个不存在的ID，会弹出异常</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="n">Traceback</span> <span class="p">(</span><span class="n">most</span> <span class="n">recent</span> <span class="n">call</span> <span class="n">last</span><span class="p">):</span>
<span class="o">...</span>
<span class="n">DoesNotExist</span><span class="p">:</span> <span class="n">Question</span> <span class="n">matching</span> <span class="n">query</span> <span class="n">does</span> <span class="ow">not</span> <span class="n">exist</span><span class="o">.</span>

<span class="c1"># Django为主键查询提供了一个缩写：pk。下面的语句和Question.objects.get(id=1)效果一样.</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="o">&lt;</span><span class="n">Question</span><span class="p">:</span> <span class="n">What</span><span class="s1">&#39;s up?&gt;</span>

<span class="c1"># 看看我们自定义的方法用起来怎么样</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">q</span> <span class="o">=</span> <span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">q</span><span class="o">.</span><span class="n">was_published_recently</span><span class="p">()</span>
<span class="bp">True</span>

<span class="c1"># 让我们试试主键查询</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">q</span> <span class="o">=</span> <span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>

<span class="c1"># 显示所有与q对象有关系的choice集合，目前是空的，还没有任何关联对象。</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">q</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="o">&lt;</span><span class="n">QuerySet</span> <span class="p">[]</span><span class="o">&gt;</span>

<span class="c1"># 创建3个choices.</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">q</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">choice_text</span><span class="o">=</span><span class="s1">&#39;Not much&#39;</span><span class="p">,</span> <span class="n">votes</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="o">&lt;</span><span class="n">Choice</span><span class="p">:</span> <span class="n">Not</span> <span class="n">much</span><span class="o">&gt;</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">q</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">choice_text</span><span class="o">=</span><span class="s1">&#39;The sky&#39;</span><span class="p">,</span> <span class="n">votes</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="o">&lt;</span><span class="n">Choice</span><span class="p">:</span> <span class="n">The</span> <span class="n">sky</span><span class="o">&gt;</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">c</span> <span class="o">=</span> <span class="n">q</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">choice_text</span><span class="o">=</span><span class="s1">&#39;Just hacking again&#39;</span><span class="p">,</span> <span class="n">votes</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>

<span class="c1"># Choice对象可通过API访问和他们关联的Question对象</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">c</span><span class="o">.</span><span class="n">question</span>
<span class="o">&lt;</span><span class="n">Question</span><span class="p">:</span> <span class="n">What</span><span class="s1">&#39;s up?&gt;</span>

<span class="c1"># 同样的，Question对象也可通过API访问关联的Choice对象</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">q</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="o">&lt;</span><span class="n">QuerySet</span> <span class="p">[</span><span class="o">&lt;</span><span class="n">Choice</span><span class="p">:</span> <span class="n">Not</span> <span class="n">much</span><span class="o">&gt;</span><span class="p">,</span> <span class="o">&lt;</span><span class="n">Choice</span><span class="p">:</span> <span class="n">The</span> <span class="n">sky</span><span class="o">&gt;</span><span class="p">,</span> <span class="o">&lt;</span><span class="n">Choice</span><span class="p">:</span> <span class="n">Just</span> <span class="n">hacking</span> <span class="n">again</span><span class="o">&gt;</span><span class="p">]</span><span class="o">&gt;</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">q</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">count</span><span class="p">()</span>
<span class="mi">3</span>

<span class="c1"># API会自动进行连表操作，通过双下划线分割关系对象。连表操作可以无限多级，一层一层的连接。</span>
<span class="c1"># 下面是查询所有的Choices，它所对应的Question的发布日期是今年。（重用了上面的current_year结果）</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">Choice</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">question__pub_date__year</span><span class="o">=</span><span class="n">current_year</span><span class="p">)</span>
<span class="o">&lt;</span><span class="n">QuerySet</span> <span class="p">[</span><span class="o">&lt;</span><span class="n">Choice</span><span class="p">:</span> <span class="n">Not</span> <span class="n">much</span><span class="o">&gt;</span><span class="p">,</span> <span class="o">&lt;</span><span class="n">Choice</span><span class="p">:</span> <span class="n">The</span> <span class="n">sky</span><span class="o">&gt;</span><span class="p">,</span> <span class="o">&lt;</span><span class="n">Choice</span><span class="p">:</span> <span class="n">Just</span> <span class="n">hacking</span> <span class="n">again</span><span class="o">&gt;</span><span class="p">]</span><span class="o">&gt;</span>

<span class="c1"># 使用delete方法删除对象</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">c</span> <span class="o">=</span> <span class="n">q</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">choice_text__startswith</span><span class="o">=</span><span class="s1">&#39;Just hacking&#39;</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">c</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>
</pre></div>


<p>关于模型的使用就暂时先介绍这么多。这部分内容是Django项目的核心，也是动态网站与数据库交互的核心，对于初学者，再难理解也要理解。</p>
<h2 id="admin">五、admin后台管理站点</h2>
<p>很多时候，我们不光要开发针对客户使用的前端页面，还要给后台管理人员提供相应的管理界面。但是大多数时候为你的团队或客户编写用于增加、修改和删除内容的后台管理站点是一件非常乏味的工作并且没有多少创造性，而且也需要花不少的时间和精力。Django最大的优点之一，就是体贴的为你提供了一个基于项目model创建的一个后台管理站点admin。这个界面只给站点管理员使用，并不对大众开放。虽然admin的界面可能不是那么美观，功能不是那么强大，内容不一定符合你的要求，但是它是免费的、现成的，并且还是可定制的，有完善的帮助文档，那么，你还要什么自行车？</p>
<h3 id="1">1. <strong>创建管理员用户</strong></h3>
<p>首先，我们需要通过下面的命令，创建一个可以登录admin站点的用户：</p>
<div class="codehilite"><pre><span></span>$ python manage.py createsuperuser
</pre></div>


<p>输入用户名：</p>
<div class="codehilite"><pre><span></span><span class="n">Username</span><span class="o">:</span> <span class="n">admin</span>
</pre></div>


<p>输入邮箱地址：</p>
<div class="codehilite"><pre><span></span>Email address: xxx@xxx.xxx
</pre></div>


<p>输入密码：</p>
<div class="codehilite"><pre><span></span>Password: **********
Password (again): *********
Superuser created successfully.
</pre></div>


<p>注意：Django1.10版本后，超级用户的密码强制要求具备一定的复杂性，不能再偷懒了。</p>
<h3 id="2">2. <strong>启动开发服务器</strong></h3>
<p>服务器启动后，在浏览器访问<code>http://127.0.0.1:8000/admin/</code>。你就能看到admin的登陆界面了：</p>
<p><img alt="image.png-13.9kB" src="http://static.zybuluo.com/feixuelove1009/gooji341rw0c46mtjqjva6jo/image.png" /></p>
<p>在实际环境中，为了站点的安全性，我们不能将管理后台的url随便暴露给他人，不能用<code>/admin/</code>这么简单的路径。</p>
<p>打开根url路由文件<code>mysite/urls.py</code>，修改其中admin.site.urls对应的正则表达式，换成你想要的，比如：</p>
<div class="codehilite"><pre><span></span><span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="kn">import</span> <span class="n">url</span>
<span class="kn">from</span> <span class="nn">django.contrib</span> <span class="kn">import</span> <span class="n">admin</span>

<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
    <span class="n">url</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^my/set/&#39;</span><span class="p">,</span> <span class="n">admin</span><span class="o">.</span><span class="n">site</span><span class="o">.</span><span class="n">urls</span><span class="p">),</span>
<span class="p">]</span>
</pre></div>


<p>这样，我们必须访问<code>http://127.0.0.1:8000/my/set/</code>才能进入admin界面。</p>
<h3 id="3-admin">3. <strong>进入admin站点</strong></h3>
<p>利用刚才建立的admin账户，登陆admin，你将看到如下的界面：</p>
<p><img alt="image.png-49.8kB" src="http://static.zybuluo.com/feixuelove1009/71xzz5ftkvd92ex3eo8jv8ie/image.png" /></p>
<p>当前只有两个可编辑的内容：groups和users。它们是<code>django.contrib.auth</code>模块提供的身份认证框架。</p>
<h3 id="4-admin">4. <strong>在admin中注册投票应用</strong></h3>
<p>现在还无法看到投票应用，必须先在admin中进行注册，告诉admin站点，请将polls的模型加入站点内，接受站点的管理。</p>
<p>打开<code>polls/admin.py</code>文件，加入下面的内容：</p>
<div class="codehilite"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib</span> <span class="kn">import</span> <span class="n">admin</span>
<span class="kn">from</span> <span class="nn">.models</span> <span class="kn">import</span> <span class="n">Question</span>

<span class="n">admin</span><span class="o">.</span><span class="n">site</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">Question</span><span class="p">)</span>
</pre></div>


<h3 id="4-admin_1">4. <strong>admin站点的主要功能</strong></h3>
<p>注册question模型后，刷新admin页面就能看到Question栏目了。</p>
<p><img alt="image.png-37.9kB" src="http://static.zybuluo.com/feixuelove1009/cc9weiavx8dvpuusfk513skl/image.png" /></p>
<p>点击“Questions”，进入questions的修改列表页面。这个页面会显示所有的数据库内的questions对象，你可以在这里对它们进行修改。看到下面的<code>“What’s up?”</code>了么？它就是我们先前创建的一个question对象，并且通过<code>__str__</code>方法的帮助，显示了较为直观的信息，而不是一个冷冰冰的对象类型名称。</p>
<p><img alt="image.png-31.8kB" src="http://static.zybuluo.com/feixuelove1009/9g6wo9cfa5fipgmvo335dp2w/image.png" /></p>
<p>下面，点击<code>What’s up?</code>进入编辑界面：</p>
<p><img alt="image.png-47.6kB" src="http://static.zybuluo.com/feixuelove1009/wzeve3hf28vyow8bj8ow1iwl/image.png" /></p>
<p>这里需要注意的是：</p>
<ul>
<li>页面中的表单是由Question模型自动生成的。</li>
<li>不同的模型字段类型(DateTimeField, CharField)会表现为不同的<code>HTML input</code>框类型。</li>
<li>每一个<code>DateTimeField</code>都会自动生成一个可点击链接。日期是Today，并有一个日历弹出框；时间是Now，并有一个通用的时间输入列表框。</li>
</ul>
<p>在页面的底部，则是一些可选项按钮：</p>
<ul>
<li><code>delete</code>：弹出一个删除确认页面</li>
<li><code>save and add another</code>：保存当前修改，并加载一个新的空白的当前类型对象的表单。</li>
<li><code>save and continue editing</code>：保存当前修改，并重新加载该对象的编辑页面。</li>
<li><code>save</code>：保存修改，返回当前对象类型的列表页面。</li>
</ul>
<p>如果<code>Date published</code>字段的值和你在前面教程创建它的时候不一致，可能是你没有正确的配置<code>TIME_ZONE</code>，在国内，通常是8个小时的时间差别。修改TIME_ZONE配置并重新加载页面，就能显示正确的时间了。</p>
<p>在页面的右上角，点击<code>History</code>按钮，你会看到你对当前对象的所有修改操作都在这里有记录，包括修改时间和操作人员，如下图所示：</p>
<p><img alt="image.png-29.6kB" src="http://static.zybuluo.com/feixuelove1009/k1ofn93wzepcpemniygcc3tw/image.png" /></p>
            </div>
            <!-- 教程正文主体部分结束 -->

            <hr />


            <!-- 打赏部分开始 -->

















            <!-- 打赏部分结束 -->


            <!-- 教程导航条 -->
            <div class="row">
                
                    <a class="pull-left" href="87.html">
                        <i class="glyphicon glyphicon-chevron-left"></i>Part 1：请求与响应</a>
                

                
                    <a class="pull-right" href="89.html">
                        Part 3：视图和模板<i class="glyphicon glyphicon-chevron-right"></i></a>
                
            </div>
            <!-- 教程导航条结束 -->


            <hr />

            <!-- 评论区-->
            

            <!-- 显示评论条数-->
            <div class="row">
                
                <h3>评论总数：  23</h3>
                <hr />
            </div>

            <!-- 评论表单区-->
            <div class="row">
                
                
                <a href="88.html">登录后方可评论</a>
                
            </div>
            <!-- 评论表单区结束-->

            <hr />

            <!-- 评论显示区-->
            <div class="row">
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tva2.sinaimg.cn/crop.41.0.446.446.50/e2f9f9cdjw8f2xmhpvecpj20go0go0sw.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >这才是真正的Django教程</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    海上有个树荫_hhh
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2018年3月13日 00:39</em>
                                        <a href="/reply/300">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>被教程感动
学习的路上</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tva3.sinaimg.cn/crop.0.0.749.749.50/ba35eb75jw8f7cpn7eppgj20ku0ktmz6.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >江哥 关于连接mysql的问题</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    二笔小聪聪
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2018年2月14日 12:45</em>
                                        <a href="/reply/216">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>江哥 我连接Mysql
DATABASES = {
    &#39;default&#39;: {
        &#39;ENGINE&#39;: &#39;django.db.backends.mysql&#39;,
        &#39;NAME&#39;: &#39;mysite&#39;,
        &#39;HOST&#39;: &#39;192.168.1.1&#39;,
        &#39;USER&#39;: &#39;root&#39;,
        &#39;PASSWORD&#39;: &#39;pwd&#39;,
        &#39;PORT&#39;: &#39;3306&#39;,
    }
} 用的也是这个代码 
但是显示连接超时了.... 是什么情况...</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tva4.sinaimg.cn/crop.0.0.664.664.50/dfedbde6jw8f9zzb6sxq0j20ig0igwfp.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >求问</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    _Lure
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2018年2月5日 15:45</em>
                                        <a href="/reply/192">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>请问修改question和Choice这两个类的代码和用于判断问卷是否最近时间段内发布度的代码是在同一个文件里吗？？
命令行始终是 &lt;QuerySet [&lt;Question: Question object&gt;]&gt;</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 4em">
                        <div>
                            <img src="http://tva4.sinaimg.cn/crop.0.0.664.664.50/dfedbde6jw8f9zzb6sxq0j20ig0igwfp.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >回复</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    _Lure
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    _Lure
                                                
                                            </span>
                                        
                                        <em>2018年2月5日 17:26</em>
                                        <a href="/reply/193">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>已经解决了</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tva4.sinaimg.cn/crop.0.0.664.664.50/dfedbde6jw8f9zzb6sxq0j20ig0igwfp.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >求问求问</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    _Lure
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2018年2月1日 15:40</em>
                                        <a href="/reply/180">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>博主你好：
为什么改了model.py ,改成了str方法，在命令行里打印出来还是
&lt;QuerySet [&lt;Question: Question object&gt;]&gt;</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 4em">
                        <div>
                            <img src="http://tvax1.sinaimg.cn/crop.79.178.566.566.50/005PMdg8ly8fjzip8l3ibj30k00scgr3.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >用的是Python2.7？</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    大江东流奔腾不息<span class="label label-danger">&nbsp;博主</span>
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    _Lure
                                                
                                            </span>
                                        
                                        <em>2018年2月1日 21:48</em>
                                        <a href="/reply/181">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>在python2版本中使用的是__unique__</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 8em">
                        <div>
                            <img src="http://tva4.sinaimg.cn/crop.0.0.664.664.50/dfedbde6jw8f9zzb6sxq0j20ig0igwfp.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >回复</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    _Lure
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    大江东流奔腾不息<span class="label label-danger">&nbsp;博主</span>
                                                
                                            </span>
                                        
                                        <em>2018年2月5日 15:32</em>
                                        <a href="/reply/191">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>用的就是python3啊</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 12em">
                        <div>
                            <img src="http://tva4.sinaimg.cn/crop.0.0.996.996.50/6dd64443jw8fc9lpx2phjj20ro0rptbg.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >跟你一样</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    可乐a柠檬
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    _Lure
                                                
                                            </span>
                                        
                                        <em>2018年2月6日 10:03</em>
                                        <a href="/reply/196">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>跟你一个问题，解决了么，谢谢</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tva1.sinaimg.cn/crop.0.0.180.180.50/871fe6a5jw1e8qgp5bmzyj2050050aa8.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >老师，为什么在后台看不到不同APP下的数据库模板内容？</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    hello_南极
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2018年1月19日 20:39</em>
                                        <a href="/reply/144">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>在同一个项目下创建不同的APP，在每个APP中都写入的不同的数据库模型，但后台为什么看不到呢，这是为什么？</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 4em">
                        <div>
                            <img src="http://tva1.sinaimg.cn/crop.0.0.180.180.50/871fe6a5jw1e8qgp5bmzyj2050050aa8.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >好像是没有注册！！</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    hello_南极
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    hello_南极
                                                
                                            </span>
                                        
                                        <em>2018年1月19日 21:03</em>
                                        <a href="/reply/145">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>好像是没有注册！！</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tva2.sinaimg.cn/crop.0.0.180.180.50/e329c853jw8e8ul3goqp0j2050050jr6.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >询问一下 shell问题。</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    __殇_傷
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2018年1月16日 15:48</em>
                                        <a href="/reply/129">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>当我启动shell的时候，显示如下：
Python 3.6.2 (v3.6.2:5fd33b5, Jul  8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32
&gt;&gt;&gt; Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.
(InteractiveConsole)

无法进行任何操作？请问这是为什么？网上没有找到答案。。。谢谢</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tva1.sinaimg.cn/crop.0.0.180.180.50/871fe6a5jw1e8qgp5bmzyj2050050aa8.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >admin里面的操作相当于是在数据库？</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    hello_南极
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2018年1月15日 13:13</em>
                                        <a href="/reply/121">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>admin里面的操作相当于是在数据库？</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 4em">
                        <div>
                            <img src="http://tvax1.sinaimg.cn/crop.79.178.566.566.50/005PMdg8ly8fjzip8l3ibj30k00scgr3.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >是的</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    大江东流奔腾不息<span class="label label-danger">&nbsp;博主</span>
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    hello_南极
                                                
                                            </span>
                                        
                                        <em>2018年1月15日 21:03</em>
                                        <a href="/reply/125">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>admin本质上就是个图形化的数据库访问接口</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tva1.sinaimg.cn/crop.0.0.540.540.50/b5871ccbjw8ehdwklav4rj20f00f0q3k.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >需要帮忙给看看</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    daziduan-hard-reg
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2018年1月2日 07:02</em>
                                        <a href="/reply/105">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>我们需要再运行下一个命令：

$ python manage.py makemigrations polls

之后我的pycharm给的是一个warning
WARNINGS:
?: (1_8.W001) The standalone TEMPLATE_* settings were deprecated in Django 1.8 and the TEMPLATES dictionary takes precedence. You must put the values
 of the following settings into your default TEMPLATES dict: TEMPLATE_DIRS.
App &#39;polls&#39; could not be found. Is it in INSTALLED_APPS?

是哪里出错了吗？</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 4em">
                        <div>
                            <img src="http://tvax1.sinaimg.cn/crop.79.178.566.566.50/005PMdg8ly8fjzip8l3ibj30k00scgr3.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >要注册app</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    大江东流奔腾不息<span class="label label-danger">&nbsp;博主</span>
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    daziduan-hard-reg
                                                
                                            </span>
                                        
                                        <em>2018年1月2日 09:31</em>
                                        <a href="/reply/106">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>将‘polls’添加到INSTALLED_APPS里面。</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tva2.sinaimg.cn/crop.0.0.720.720.50/6a65e919jw8eko1hrly1kj20k00k0759.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >SyntaxError: invalid syntax</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    闹够L没有__
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2017年12月12日 16:49</em>
                                        <a href="/reply/85">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>通过运行makemigrations命令出现错误SyntaxError: invalid syntax。请问是什么情况？</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 4em">
                        <div>
                            <img src="http://tvax1.sinaimg.cn/crop.79.178.566.566.50/005PMdg8ly8fjzip8l3ibj30k00scgr3.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >信息太少，无法定位问题</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    大江东流奔腾不息<span class="label label-danger">&nbsp;博主</span>
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    闹够L没有__
                                                
                                            </span>
                                        
                                        <em>2017年12月12日 19:54</em>
                                        <a href="/reply/86">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>一切皆有可能....</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tvax3.sinaimg.cn/crop.0.0.664.664.50/006a9ofEly8fgarvqbvonj30ig0igmy0.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >刷新admin页面为什么没有看到Question栏目</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    兰若行迹
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2017年12月7日 12:18</em>
                                        <a href="/reply/73">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>新手，按照你的步骤没有看到question，是刷新的方式不对吗？</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 4em">
                        <div>
                            <img src="http://tvax1.sinaimg.cn/crop.79.178.566.566.50/005PMdg8ly8fjzip8l3ibj30k00scgr3.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >再检查一下你的代码</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    大江东流奔腾不息<span class="label label-danger">&nbsp;博主</span>
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    兰若行迹
                                                
                                            </span>
                                        
                                        <em>2017年12月7日 19:06</em>
                                        <a href="/reply/75">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>问题都处在细节上...</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 8em">
                        <div>
                            <img src="http://tvax3.sinaimg.cn/crop.0.0.664.664.50/006a9ofEly8fgarvqbvonj30ig0igmy0.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >嗯</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    兰若行迹
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    大江东流奔腾不息<span class="label label-danger">&nbsp;博主</span>
                                                
                                            </span>
                                        
                                        <em>2017年12月10日 22:24</em>
                                        <a href="/reply/78">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>嗯，解决了，谢谢</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 4em">
                        <div>
                            <img src="http://tva4.sinaimg.cn/crop.0.0.996.996.50/005u6NFRjw8fdcctpuu7qj30ro0rowgx.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >检查下，可能是你没有在admin里面注册你的question模型</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    DOITMY
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    兰若行迹
                                                
                                            </span>
                                        
                                        <em>2018年1月8日 13:05</em>
                                        <a href="/reply/115">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>在polls/admin里面加上如下代码
from .models import Question

admin.site.register(Question)</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tva1.sinaimg.cn/crop.79.114.313.313.50/a33d1690jw8eqgfhcx55fj20c80fogmy.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >admin的用户名密码忘了怎么办</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    氷湗de心
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2017年11月27日 11:51</em>
                                        <a href="/reply/65">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>admin的用户名密码忘了怎么办
才几天没登陆</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 4em">
                        <div>
                            <img src="http://tvax1.sinaimg.cn/crop.79.178.566.566.50/005PMdg8ly8fjzip8l3ibj30k00scgr3.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >再创建一个</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    大江东流奔腾不息<span class="label label-danger">&nbsp;博主</span>
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    氷湗de心
                                                
                                            </span>
                                        
                                        <em>2017年11月27日 16:12</em>
                                        <a href="/reply/66">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>python manage.py createsuperuser</p>
                        </div>
                    </div>
                
            </div>
            <!-- 评论显示区结束-->

            <!-- 评论区结束-->

        </div>
        <!-- 右侧正文栏结束 -->

      </div>
    </div>




    <div id="back-to-top" >
        <span class="glyphicon glyphicon-arrow-up"></span>
    </div>


    <footer id="footer" class="midnight-blue">
        <div class="container-fluid" style="font-size: smaller">
            <div class="row footer-1">
                <div class="col-md-2">
                    Copyright &copy; 2018.刘江的官方网站
                </div>
                <div class="col-md-3">
                    托管于<a target="_blank" href="https://www.aliyun.com/">阿里云</a>
                    &nbsp;&nbsp;&nbsp;&nbsp;
                    <a target="_blank" href="http://www.miitbeian.gov.cn/">京ICP备17055098号</a>
                </div>
                <div class="col-md-2">
                    <a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=11010602120033">

                        <span><img style="display: inline;margin: 0 auto;" src="/static/images/ghs.png" />京公网安备11010102002019号</span>
                    </a>
                </div>
                <div class="col-md-5">
                    <ul class="pull-right">
                        <li><a href="/blog/">返回首页</a></li>
                        <li><a href="/about/">关于博主</a></li>
                        <li><a href="#">常见问题</a></li>
                        <li><a href="/contact/" target="_blank">广告合作</a></li>
                        <li><a href="/contact/" target="_blank">联系方式</a></li>
                        <li><a href="#">使用许可</a></li>
                    </ul>
                </div>
            </div>







        </div>
    </footer><!--/#footer-->

    <script src="/static/js/jquery.js"></script>
    <script src="/static/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>


    <script>


        //为新闻添加访问量
        function count_visiting(news_id){
            var to_url = "/news/visiting/"+news_id;
            jQuery.get(to_url);
        }


        $("#donate").click(function () {
            $("#donate_page").toggleClass('hidden');
        });



        <!-- 导航条对应条目active -->
        $(document).ready(function () {

            $('.navbar-nav').find('a').each(function () {
                if (this.href == document.location.href || document.location.href.search(this.href) >= 0) {
                    $(this).parent().addClass('active'); // this.parent.className = 'active';
                }
            });

            $('table').addClass('table table-bordered table-hover');

            $('img').addClass('img-responsive');

            $('#back-to-top').click(function () {
                window.scrollTo(0,0);
            });

        });

    

        $('button.navbar-toggle').click(function () {
            $('#my-navbar').css("background","#337ab7")
        });
        
    </script>

</body>

</html>